<template>  
  <view class="container"> 
   
    <form @submit="onSubmit">  
	 <view class="form-item">
	   <label>昵称:</label>  
	   <input v-model="nickname" type="text" placeholder="请输入昵称" />  
	 </view>  
      <!-- <view class="form-item">  
        <label>注册手机号:</label>  
        <input v-model="phone" placeholder="用于与搭配师沟通" type="text"/>  
      </view> -->   
      <view class="form-item">  
        <label>所在地区:</label>  
		<view class="uni-list-cell-db">
			<uni-data-picker
				
				popup-title="请选择所在地区"
				:localdata="classDataTree"
				v-model="classValue"
				@change="onchange"
				@nodeclick="onnodeclick"
				@popupopened="onpopupopened"
				@popupclosed="onpopupclosed"
				@inputclick="inputclick"
			></uni-data-picker>
			<!-- <picker @change="bindPickerChange" :value="index" :range="array">
				<view class="uni-input">{{array[index]}}</view>
			</picker> -->
		</view>
      </view>  
      
      <view class="form-item">  
        <label>年龄:</label>  
        <input v-model="age" type="number" placeholder="20" />  
      </view>  
	  
      <view class="form-item">  
        <label for="gender">性别：</label>
       <radio-group id="gender" name="gender" @change="handleGenderChange">
         <label v-for="(item, index) in genders" :key="index" class="radio-label">
           <radio :value="item.value" :checked="item.checked" color="#FFC90E" style="transform:scale(0.7)" />
           {{ item.text }}
         </label>
       </radio-group>

      </view>  
      
      <view class="form-item">  
        <label>身高/厘米:</label>  
        <input v-model="height" type="number" placeholder="165" />  
      </view>  
      
      <view class="form-item">  
        <label>体重/公斤:</label>  
        <input v-model="weight" type="number" placeholder="55" />  
      </view>  
      
      <view class="form-item">  
        <label>你常穿什么品牌？</label> </view> 
        <view class="bandsize">
		<picker @change="bindPickerChange1" :value="index1" :range="band">
			<view class="uni-input">{{band[index1]}}</view>
		</picker>
		<picker @change="bindPickerChange2" :value="index2" :range="sizes">
			<view class="uni-input">{{sizes[index2]}}</view>
		</picker>
      </view>  
	   
    <view class="fuse">肤色</view>
    <view class="form-group">
        <!-- 单选框组 -->
      	<radio-group @change="handleRadioChange1">
      	    <label v-for="(item, index) in skincolors" :key="index" class="radio-label">
      		    <radio :value="item.value" :checked="item.checked" color="#FFC90E"  style="transform:scale(0.7)"/> {{ item.text }}
      	    </label>
      	</radio-group>
    </view>
	
    <view class="qise">气色</view>
    <view class="form-group">
      	<radio-group @change="handleRadioChange2">
      		<label v-for="(item, index) in facecolors" :key="index" class="radio-label">
      		    <radio :value="item.value" :checked="item.checked" color="#FFC90E"  style="transform:scale(0.7)"/> {{ item.text }}
      		</label>
      	</radio-group>
    </view>
	
    <view class="haircolor">发色</view>
    <view class="form-group">
      	<radio-group @change="handleRadioChange3">
      		<label v-for="(item, index) in haircolors" :key="index" class="radio-label">
      		    <radio :value="item.value" :checked="item.checked" color="#FFC90E"  style="transform:scale(0.7)"/> {{ item.text }}
      		</label>
      	</radio-group>
    </view>
	
	<view class="hairquality">发质</view>
	<view class="form-group">
	  	<radio-group @change="handleRadioChange4">
	  		<label v-for="(item, index) in hairqualitys" :key="index" class="radio-label">
	  		    <radio :value="item.value" :checked="item.checked" color="#FFC90E" style="transform:scale(0.7)" /> {{ item.text }}
	  		</label> 
	  	</radio-group>
	</view>
	
	<view class="eyecolor">眼珠色</view>
	<view class="form-group">
	  	<radio-group @change="handleRadioChange5">
	  	    <label v-for="(item, index) in eyecolors" :key="index" class="radio-label">
	  	        <radio :value="item.value" :checked="item.checked " color="#FFC90E"  style="transform:scale(0.7)"/> {{ item.text }}
	  	    </label>
	  	</radio-group>
	</view>
	
    <view class="form-item1">  
        <button form-type="submit">点击确认</button>  
    </view>  
    </form>  
  </view>  
</template>  

<script>  
import {classDataTree} from"/pages/picker-region.js";
import { toRaw } from 'vue';
import setting from "../../setting";

export default {  
  data() {  
        return {  
            nickname: '', // 昵称
            classValue: '120101', // 设置默认值或通过后端获取
            classDataTree: classDataTree ,
            title: 'picker',
            band:['李宁','阿迪达斯','鸿星尔克','耐克','香奈儿','迪奥','纪梵希','圣罗兰','Zara','H&M'],
            sizes:['S','M','L','XL','XXL','XXXL'],
            index: 0,
            index1: 0,
            index2: 0,
            age: '20', // 年龄
            gender: '女', // 性别默认获取********
			genders :[
			    { text: '男', value: '男'},
			    { text: '女', value: '女'},
			],
            height: '', // 身高
            weight: '', // 体重
            brand: '', // 品牌
            size: '', // 尺码
            skinColor: '', // 肤色
            faceColor: '', // 气色
            hairColor: '', // 发色
            hairQuality: '', // 发质
            eyeColor: '', // 眼珠色
            skinColorText: '', 
            faceColorText: '', 
            hairColorText: '', 
            hairQualityText: '', 
            eyeColorText: '', 
            skincolors: [
                { text: '白皙透明', value: 'bai' },
                { text: '黄皮偏白', value: 'huangbai'},
                { text: '黄皮', value: 'huang' },
                { text: '黄皮偏黑', value: 'huanghei' },
            ],
            facecolors: [
                { text: '面色红润显得红扑扑', value: 'red' },
                { text: '双颊正面略显红', value: 'little'},
                { text: '双颊几乎无血色', value: 'white' },
            ],
            haircolors: [
                { text: '发色深黑', value: 'color1' },
                { text: '黑发为主略显棕黄', value: 'color2' },
                { text: '灰发或银灰', value: 'color3' },
                { text: '棕色或金黄或咖啡色', value: 'color4' },
                { text: '红色或紫红', value: 'color5' },
            ],
            hairqualitys: [
                { text: '亮泽且发丝偏硬', value: 'quality1' },
                { text: '亮泽且发丝细软', value: 'quality2'},
                { text: '偏干且发丝偏硬', value: 'quality3' },
                { text: '偏干且发丝细软', value: 'quality4' },
            ],
            eyecolors: [
                { text: '黑棕', value: 'eyecolor1'},
                { text: '棕黄', value: 'eyecolor2' },
            ],
			 userId: '', // 存储用户 ID
        };
    },
  mounted() {
	const userId = uni.getStorageSync('user_id');
	        // 如果 userId 存在，则调用 fetchUserData 获取数据
	        if (userId) {
	            this.userId = userId;
	            this.fetchUserData(userId); // 根据 userId 获取数据
	        } else {
	            console.error('未找到用户ID');
	        }
  },
  methods: { 
	 // 查找 value 对应的路径
	onchange(e){
		const rawValue = toRaw(e.detail.value[2]); // 获取代理对象的原始值
		this.classValue = rawValue.value;
	},
	findValuePath(nodes, targetValue, currentPath = []) {
	  for (const node of nodes) {
	    const path = [...currentPath, node.value];
	    if (node.value === targetValue) {
	      return path;
	    }
	    if (node.children) {
	      const foundPath = this.findValuePath(node.children, targetValue, path);
	      if (foundPath) {
	        return foundPath;
	      }
	    }
	  }
	  return null;
	},
	fetchUserData(userId) {
			uni.request({
			    method: 'GET',
			    url: `${setting.url}/api/get_body_measurements`,
				data: {
					user_id: userId  // 将 user_id 参数传递到请求中
				}
			})
			.then((response) => {
			    console.log("从后端获取的数据:", response.data);
			    const data = response.data;
			    // 根据返回的数据更新字段
			    this.nickname = data[13] || 'Alice'; // 用户名
			    const classValueFromBackend = String(data[2]) || '120101';
			    const path = this.findValuePath(classDataTree, classValueFromBackend);
			    this.classValue = path || ['120000', '120100', '120101'];
			    this.age = data[3]; // 年龄
			    this.height = data[4]; // 身高
			    this.weight = data[5]; // 体重
			    this.brand = data[6]; // 品牌
			    this.index1 = this.band.indexOf(this.brand);
			    this.size = data[7]; // 尺码
			    this.index2 = this.sizes.indexOf(this.size);
			    this.skinColor = data[8]; // 肤色
			    
			    this.faceColor = data[9]; // 气色
			    this.hairColor = data[10]; // 发色
			    this.hairQuality = data[11]; // 发质
			    this.eyeColor = data[12]; // 眼珠色
			    this.gender=data[14];
			    //性别
			    this.genders.forEach(item => {
			    	item.checked = item.text === data[14];
			    });
			    // 更新肤色选项的选中状态
			    this.skincolors.forEach(item => {
			        item.checked = item.text === data[8];
			    });
			    // 更新气色选项的选中状态
			    this.facecolors.forEach(item => {
			        item.checked = item.text === data[9];
			    });
			    //发色
			    this.haircolors.forEach(item => {
			        item.checked = item.text === data[10];
			    });
			    //发质
			    this.hairqualitys.forEach(item => {
			    	item.checked = item.text === data[11];
			    });
			    this.eyecolors.forEach(item => {
			        item.checked = item.text === data[12];
			    });
			})
			.catch((error) => {
			    console.log('获取用户数据失败:', error);
			    throw error; // 将错误继续抛出，以便外部捕获
			});
				   
	},

	handleGenderChange(e) {
	    this.gender = e.detail.value;
	},
	
	  handleRadioChange1(e) {
	    const selectedValue = e.detail.value;
	    this.skinColor = selectedValue; 
	    const selectedSkinColor = this.skincolors.find(item => item.value === selectedValue);
	    this.skinColorText = selectedSkinColor ? selectedSkinColor.text : ''; 
	    this.skincolors.forEach(item => {
	      item.checked = item.value === selectedValue;
	    });
	  },
	
	  handleRadioChange2(e) {
	      const selectedValue = e.detail.value;
	      this.faceColor = selectedValue;
	      const selectedFaceColor = this.facecolors.find(item => item.value === selectedValue);
	      this.faceColorText = selectedFaceColor ? selectedFaceColor.text : ''; 
	      this.facecolors.forEach(item => {
	        item.checked = item.value === selectedValue;
	      });
	  },
	  
	  handleRadioChange3(e) {
	      const selectedValue = e.detail.value;
	      this.hairColor = selectedValue; 
	      const selectedHairColor = this.haircolors.find(item => item.value === selectedValue);
	      this.hairColorText = selectedHairColor ? selectedHairColor.text : ''; 
	      this.haircolors.forEach(item => {
	        item.checked = item.value === selectedValue;
	      });
	  },
	  
	  handleRadioChange4(e) {
	      const selectedValue = e.detail.value;
	      this.hairQuality = selectedValue; 
	      const selectedHairQuality = this.hairqualitys.find(item => item.value === selectedValue);
	      this.hairQualityText = selectedHairQuality ? selectedHairQuality.text : ''; 
	      this.hairqualitys.forEach(item => {
	        item.checked = item.value === selectedValue;
	      });
	  },
	  
	handleRadioChange5(e) {
	      const selectedValue = e.detail.value;
	      this.eyeColor = selectedValue; 
	      const selectedEyeColor = this.eyecolors.find(item => item.value === selectedValue);
	      this.eyeColorText = selectedEyeColor ? selectedEyeColor.text : ''; 
		  this.eyecolors.forEach(item => {
	        item.checked = item.value === selectedValue;
	      });
	  },

	 bindPickerChange: function(e) {
	        console.log('picker发送选择改变，携带值为', e.detail.value)
	        this.index = e.detail.value
	},
	
	bindPickerChange1: function(e) {
	        console.log('picker发送选择改变，携带值为', e.detail.value)
	        this.index1 = e.detail.value
	},
	
	bindPickerChange2: function(e) {
	           console.log('picker发送选择改变，携带值为', e.detail.value)
	           this.index2 = e.detail.value
	},
    onSubmit(e) {
      this.brand = this.band[this.index1];
      this.size = this.sizes[this.index2];
    
      // 提交表单的逻辑
      const userId = uni.getStorageSync('user_id');  // 获取存储的 user_id
      const data = {
        userId: userId,
        nickname: this.nickname,
        region: this.classValue,
        age: this.age,
        gender: this.gender,
        height: this.height,
        weight: this.weight,
        brand: this.brand,
        skinColorText: this.skinColorText,
        faceColorText: this.faceColorText,
        hairColorText: this.hairColorText,
        hairQualityText: this.hairQualityText,
        eyeColorText: this.eyeColorText,
        size: this.size,
      };
    
      console.log('提交数据:', data);
    
      // 使用 fetch 提交到后端接口
      uni.request({
		url: `${setting.url}/api/submit`,
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',  // 发送 JSON 格式数据
        },
        data:data,  // 将数据转为 JSON 字符串发送
      })
	  .then((response) => {
          console.log('更新成功:', response);
          uni.showToast({
            title: '更新成功',
            icon: 'success',
            duration: 1500,
            complete: () => {
              // 在提示信息显示完毕后跳转页面
              uni.switchTab({
                url: '/pages/UserCenter/UserCenter' // 添加随机参数
              });
            }
          });
        })
        .catch((error) => {
			console.error('更新失败:', error);
			uni.showToast({
			  title: '更新失败',
			  icon: 'none'
			});
		});
    }
}
};
</script>  

<style scoped>  
.container {  
  padding: 20px;  
  background-color: #FFFCED;
  
}
.title {
	font-size: 14px;
	font-weight: bold;
	margin: 20px 0 5px 0;
}
.uni-list{
	display: flex;
}

.form-item {  
  display: flex;
  margin-bottom: 15rpx;  
  align-items: center; 
  box-shadow: 2rpx 2rpx 4rpx rgba(0,0,0,0.4);
  border-radius: 10rpx;
  padding:8rpx;
  gap:10px;
  background-color: #FFF;
}  

.gender {  
  display: flex;  
  align-items: center;  
}  

.color-options {  
  display: flex;  
  flex-direction: column;  
}  

.uni-list-cell-db{
	background-color:#FFF;
}

.bandsize{
	display: flex; 
	margin: 0px 50px;
	background-color:#f5f5f5;
}

.uni-input{
	margin:0 30px;
}

.form-group {
	display: flex; 
    margin-bottom: 15rpx;
	box-shadow: 2rpx 2rpx 4rpx rgba(0,0,0,0.4);
	border-radius: 10rpx;
	padding:8rpx;
	background-color: #FFF;
}

.radio-label {
    display: inline-block; /* 将标签设为内联块元素 */
    margin-right: 30px; /* 设置右侧外边距以控制间距 */
}

input{
	background-color:#FFF;
}

.form-item1 {  
  display: flex;
  margin-bottom: 15rpx;  
  align-items: center; 
  border-radius: 10rpx;
  padding:8rpx;
  gap:10px;
}  

button {          
  border: 1rpx solid black;
  background-color: #FFF200;
  border-radius: 10rpx;
  color: black;
  font-size:32rpx;
  width: 40%;
  box-shadow: 4rpx 4rpx 3rpx rgba(0, 0, 0, 0.3);  
  margin-top: 20rpx;
}  

.fuse,.qise,.haircolor,.eyecolor,.hairquality{
	padding: 8rpx;
	margin-top: 8rpx;
}

</style>